import axios from 'axios'
import {useRequestStore, useUserStore} from '@/store'
import {checkStatus} from './checkStatus'
import {publicEncryptedData} from '@/utils/encrypted'
import {h} from 'vue'

export const createAxiosInterceptor = http => {
  // 请求拦截
  http.interceptors.request.use(config => {
    const token = useUserStore().token || localStorage.getItem('X-token'),
      time = Math.round(new Date().getTime() / 1000)
    token ? config.headers['X-token'] = token : ''
    if (config.data) {
      console.log(config.data)
      config.data['time'] = time
      config.data = {data: publicEncryptedData(JSON.stringify(config.data), 'encrypt')}
    } else if (config.params) {
      console.log(config.params)
      config.params['time'] = time
      config.params = {data: publicEncryptedData(JSON.stringify(config.params), 'encrypt')}
    }
    config.cancelToken = new axios.CancelToken(cancel => useRequestStore().setHttpRequestList(cancel))
    return config
  }, undefined)

  // 响应拦截
  http.interceptors.response.use(response => {
    console.log(response.data)
    response.data?.code !== 0 ? checkStatus(response.data.code, response.data.msg) : ''
    return response.data
  }, error => {
    let {response, code, message} = error || {}
    const msg = response && response.data && response.data.msg ? response.data.msg : ''
    const err = error.toString()
    if (message && message === 'suspend') return new Promise(() => {})
    try {
      if (code === 'ECONNABORTED' && message.indexOf('timeout') !== -1) {
        $message.error('接口请求超时，请刷新页面重试!')
        return
      }
      if (err && err.includes('Network Error')) {
        $dialog.warning({
          title: '网络异常',
          content: () => h('div', {
            class: 'pb-6'
          }, {default: () => '请检查您的网络连接是否正常' || ''}),
          positiveText: '确认',
          positiveButtonProps: {
            size: 'large'
          },
          closable: false,
          maskClosable: false,
        })
        return Promise.reject(error)
      }
    } catch (e) {
      throw new Error(e)
    }
    // 请求是否被取消
    const isCancel = axios.isCancel(error)
    !isCancel ? checkStatus(error.response && error.response.status, msg) : ''
    return Promise.reject(response?.data)
  })
}
